package com.logjun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.logjun.reggie.common.BaseContext;
import com.logjun.reggie.common.CustomException;
import com.logjun.reggie.common.R;
import com.logjun.reggie.dto.UserDto;
import com.logjun.reggie.entity.User;
import com.logjun.reggie.service.UserService;
import com.logjun.reggie.utils.RandomCode;
import com.logjun.reggie.utils.SendEmail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取验证码请求
     * @param user
     * @return
     */
    @PostMapping("/checkCode")
    public R<String> checkCode(HttpServletRequest httpServletRequest, @RequestBody User user){
        String mail = user.getMail();
        log.info("获取到的邮箱地址：{}",mail);
        //获取随即生成的验证码
        String code = RandomCode.getCode();
        log.info("生成的验证码为：{}",code);
        //保存验证码到session中
        //HttpSession session = httpServletRequest.getSession();
        //session.setAttribute("checkCode",code);
        //设置定时器，一分钟后删除验证码；
        /*Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                session.removeAttribute("checkCode");
                log.info("验证码已从session中删除");
                timer.cancel();
            }
        },5*60*1000);*/
        //向目标邮箱发送验证码
        //使用redis缓存验证码，设置过期时间
        redisTemplate.opsForValue().set(user.getMail(),code,5, TimeUnit.MINUTES);
        try {
            SendEmail.sendEmail(mail,code);
        }catch (AddressException e) {
            throw new CustomException("邮箱地址不正确");
        } catch (NoSuchProviderException e) {
            throw new CustomException("NoSuchProviderException异常");
        } catch (MessagingException e) {
            throw new CustomException("MessagingException异常");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //验证码发送后，如果查不到邮箱，则创建新的用户信息保存邮箱,
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getMail, user.getMail());
        if (!(userService.count(queryWrapper) > 0)){
            userService.save(user);
        }
        return R.success("验证码已发送，请注意检查邮箱！");
    }

    /**
     * 用户登录功能
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody UserDto user, HttpServletRequest request){
        //先获取session中的验证码，比对是否一致
        //String checkCode = (String) session.getAttribute("checkCode");
        HttpSession session = request.getSession();
        //获取缓存中的验证码
        String checkCode = (String)redisTemplate.opsForValue().get(user.getMail());
        if (null != checkCode && checkCode.equals(user.getCode())){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getMail, user.getMail());
            //根据邮箱查询，如果查询到则允许登录
            User userOne = userService.getOne(queryWrapper);
            log.info("查询到的用户信息：{}",userOne.toString());
            if (null != userOne){
                session.setAttribute("user",userOne.getId());
                log.info("获取的邮箱地址：{}",user.getMail());
                //登录成功，删除验证码
                redisTemplate.delete(user.getMail());
                return R.success(userOne);
            }else {
                //没查到值，邮箱地址不正确
                throw new CustomException("邮箱地址错误，请输入正确的邮箱地址");
            }
        }
        return R.error("验证码错误，登录失败");
    }

    /**
     * 用户登出功能
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("登出成功！");
    }
}
